#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:首次信贷年份
code:FirstLoan_year
tableName:
columnName:
groups:企业征信
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
ECRSummaryDesc002:（概要描述—拆分）
BriefDesc1:首次信贷发生年份（解析字段）
'''

import sys
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
import json

reload(sys)
sys.setdefaultencoding('utf-8')

#如果这个字段存在 但是里面的list长度为0 不包含任何dict 应该返回缺失值 不应该为0
def FormatData(tableName):
    try:
        ecr = json.loads(EC[0]["ecr"])[tableName]
        return ecr if isinstance(ecr, list) and len(ecr) > 0 else [{}]
    except:
        return [{}]

def FirstLoan_year():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']

    try:
        ECRSummaryDesc002 = FormatData('ECRSummaryDesc002')
        if ECRSummaryDesc002 == [{}]:
            return u'缺失值'
        else:
            if len(ECRSummaryDesc002) == 1:
                if ECRSummaryDesc002[0].has_key('BriefDesc1')\
                        and ECRSummaryDesc002[0]['BriefDesc1'] not in null_type_list \
                    and isYear(ECRSummaryDesc002[0]['BriefDesc1']):
                    #以开贷那年 1月1日 计算开始
                    first_loan_year = float(ECRSummaryDesc002[0]['BriefDesc1'])
                    now_year = float(datetime.datetime.now().year)
                    num = now_year - first_loan_year
                    return num
                else:
                    return u'缺失值'
            else:
                return u'缺失值'
    except:
        return u'缺失值'

def isYear(year):
    try:
        if len(year) == 4 and year.isdigit():
            return True
        else:
            return False
    except:
        return False

result = FirstLoan_year()